import {
    addUserCreditAccount,
    calendarSignRebate,
    isCalendarSignRebate,
    queryUserActivityAccount,
    queryUserCreditAccount
} from "@/apis";
import React, {useEffect, useState} from "react";
import {UserActivityAccountVO} from "@/types/UserActivityAccountVO";
import  {showCustomAlertError,showCustomAlertSuccess} from "@/app/components/showMessage";
import {string} from "prop-types";
import dynamic from "next/dynamic";
import "../globals.css"
// @ts-ignore
export function MemberCard({allRefresh}) {
    const [refresh, setRefresh] = useState(0);
     const apiHostUrl = process.env.API_HOST_URL ? process.env.API_HOST_URL : "https://117.72.71.221:8091";
    // const apiHostUrl = process.env.API_HOST_URL ? process.env.API_HOST_URL : "https://localhost:8091";

    const [dayCount, setDayCount] = useState(0)
    const [creditAmount, setCreditAmount] = useState(0)
    const [sign, setSign] = useState(false);

    const [userId, setUserId] = useState('');
    const [isPay, setIsPay] = useState(false);
    const [isDialogOpen, setIsDialogOpen] = useState(false);
    const [selectedAmount, setSelectedAmount] = useState(0);
    const OrderPage = dynamic(async () => (await import("../components/createOrder")).OrderPage);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null);

    const getParams = async () => {
        setUserId(String(new URLSearchParams(window.location.search).get('userId')));
    }

    const handleRefresh = () => {

        setRefresh(refresh + 1)
    };

    const handleRecharge = async ( amount: any) => {
        // 获取cookie的函数
        const getCookie = (name: string) => {
            const cookieArr = document.cookie.split(';');
            for (let i = 0; i < cookieArr.length; i++) {
                const cookiePair = cookieArr[i].split('=');
                if (name === cookiePair[0].trim()) {
                    return decodeURIComponent(cookiePair[1]);
                }
            }
            return null;
        };
        // 处理下单点击事件
            setLoading(true);
            setError(null);
        const cookeUserId = getCookie('loginToken');
        if (!cookeUserId) {
            window.location.href = 'login.html'; // 跳转到登录页
            return;
        }
        const queryParams = new URLSearchParams(window.location.search);
        const userId = queryParams.get('userId')
         const money = amount.valueOf(String);
        const url = `${apiHostUrl}/api/v1/alipay/create_pay_order?userId=${userId}&money=${money}`;
        // const url = 'http://127.0.0.1:8089/api/v1/raffle/activity/add_user_credit_account';
        const  productName = "积分充值 " + money +"元";

            try {
                const response = await fetch(url, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        userId: userId,
                        money: money ,// 添加 money 参数到请求体
                        productId: money.valueOf(String),
                        productName:productName
                    }) // 将请求体转换为 JSON 字符串
                });

                const json = await response.json();
                if (json.code === '0000') {
                    const formHtml = json.data; // 获取data字段中的HTML表单字符串
                    const formElement = document.createElement('div');
                    formElement.innerHTML = formHtml;
                    document.body.appendChild(formElement);
                    document.forms[0].submit(); // 自动提交表单

                } else {
                    setError(json.info); // 输出错误信息
                }
            } catch (error) {
                console.error('Error:', error);
                // @ts-ignore
                setError('请求失败，请重试。');
            } finally {
                setLoading(false);
            }

    };

    const openRechargeDialog = () => {
        setIsDialogOpen(true);
    };

    // 获取当前日期
    const currentDate = new Date();
    // 格式化日期为 YYYY年MM月DD日
    const formattedDate = currentDate.getFullYear() + '年'
        + ('0' + (currentDate.getMonth() + 1)).slice(-2) + '月'
        + ('0' + currentDate.getDate()).slice(-2) + '日';

    const queryUserActivityAccountHandle = async () => {
        const queryParams = new URLSearchParams(window.location.search);
        const result = await queryUserActivityAccount(String(queryParams.get('userId')), Number(queryParams.get('activityId')));
        // 查询账户数据
        const {code, info, data}: { code: string; info: string; data: UserActivityAccountVO } = await result.json();

        if (code != "0000") {
            // window.alert("查询活动账户额度，接口调用失败 code:" + code + " info:" + info)
            // window.alert("查询活动账户额度 : " + info)
            showCustomAlertError("查询活动账户额度",info)
            return;
        }

        // 日可抽奖额度
        setDayCount(data.dayCountSurplus)
    }

    const queryUserCreditAccountHandle = async () => {
        const queryParams = new URLSearchParams(window.location.search);
        const result = await queryUserCreditAccount(String(queryParams.get('userId')));
        const {code, info, data}: { code: string; info: string; data: number } = await result.json();

        if (code != "0000") {
            // window.alert("查询活动账户额度，接口调用失败 code:" + code + " info:" + info)
            // window.alert("查询活动账户额度失败: " + info)
            showCustomAlertError("查询活动账户额度失败",info)
            return;
        }

        // 用户积分
        setCreditAmount(data)
    }

    const calendarSignRebateHandle = async () => {
        if (sign) {
            // window.alert("今日已签到！")
            handleRefresh()
            showCustomAlertSuccess('今日已签到!', null);
            return;
        }
        const queryParams = new URLSearchParams(window.location.search);
        const result = await calendarSignRebate(String(queryParams.get('userId')));
        const {code, info}: { code: string; info: string; } = await result.json();

        if (code != "0000" && code != "0003") {
            // window.alert("日历签到返利接口，接口调用失败 code:" + code + " info:" + info)
            window.alert("日历签到失败")
            return;
        }
        if (code == "0000"){
        //       window.alert("日历签到成功")
            setTimeout(() => {
                showCustomAlertSuccess("日历签到成功",null)
            }, 1000);
             // handleRefresh();
        }


        // 设置一个3秒后执行的定时器
        const timer = setTimeout(() => {
            setSign(true);
            handleRefresh();
        }, 1000);

        // 清除定时器，以防组件在执行前被卸载
        return () => clearTimeout(timer);
    }

    const isCalendarSignRebateHandle = async () => {

        const queryParams = new URLSearchParams(window.location.search);
        const result = await isCalendarSignRebate(String(queryParams.get('userId')));
        const {code, info, data}: { code: string; info: string; data: boolean } = await result.json();

        if (code != "0000") {
            window.alert("判断是否签到接口，接口调用失败 code:" + code + " info:" + info)
            return;
        }

        setSign(data);
    }

    const [isRecordDialogOpen, setIsRecordDialogOpen] = useState(false);
    const [records, setRecords] = useState([
        {
            orderNumber: '1234567890',
            expenseType: '充值',
            amount: 50,
            description: '购买积分',
            time: "2024-08-20 08:41:37"
        }
    ]);

    const openRecordDialog = () => {
        setIsRecordDialogOpen(true);
    };

    const closeRecordDialog = () => {
        setIsRecordDialogOpen(false);
    };

    const formatDate = (dateStr: string | number | Date) => {
        const date = new Date(dateStr);
        const year = date.getFullYear();
        const month = date.getMonth() + 1;
        const day = date.getDate();
        const hours = date.getHours();
        const minutes = date.getMinutes();
        const seconds = date.getSeconds();

        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    };
    const amounts = [10, 20, 30, 50, 100, 128, 300, 648];
    const imagePaths = [
        '/10.webp',
        '/20.webp',
        '/30.webp',
        '/50.webp',
        '/100.webp',
        '/128.webp',
        '/300.webp',
        '/648.webp'
    ];

    useEffect(() => {
        getParams().then(r => {
        });

        queryUserActivityAccountHandle().then(r => {
        });

        queryUserCreditAccountHandle().then(r => {
        });

        isCalendarSignRebateHandle().then(r => {
        });
    }, [refresh, allRefresh])

    return (
        <>
            <div
                className="relative max-w-sm mx-auto bg-gradient-to-r from-blue-600 to-teal-600 rounded-xl shadow-xl overflow-hidden md:max-w-2xl mb-10">
                <div className="md:flex">
                    <div className="p-8 flex-1">
                        <a href="#"
                           className="block mt-1 text-2xl leading-tight font-semibold text-white hover:text-gray-300 transition duration-300 ease-in-out">营销会员卡</a>
                        <div className="mt-4">
                            <p className="text-lg text-gray-100 flex items-center">
                                <span className="material-icons mr-2">💰</span>
                                我的积分：
                                <span
                                    className="font-bold text-gray-100 ml-1 bg-white bg-opacity-20 rounded-full px-2 py-1">
                        {creditAmount ? creditAmount : 0}🪙
                    </span>
                            </p>
                            <p className="text-lg text-gray-100 flex items-center mt-2">
                                <span className="material-icons mr-2">🪅</span>
                                抽奖次数：
                                <span
                                    className="font-bold text-gray-100 ml-1 bg-white bg-opacity-20 rounded-full px-2 py-1">
                        {dayCount ? dayCount : 0}
                    </span>
                            </p>
                        </div>
                    </div>
                    <div className="p-8 flex items-center justify-between">
                        <button onClick={calendarSignRebateHandle} style={{cursor: "pointer"}}
                                className="bg-yellow-500 hover:bg-yellow-600 text-white font-bold py-2 px-4 rounded-full shadow-md transition duration-300 ease-in-out">
                            {sign ? "已签" : "签到"}
                        </button>
                        <div className="text-gray-100 text-md font-semibold ml-4">
                            {formattedDate}
                        </div>
                    </div>
                </div>
                <div className="absolute bottom-4 right-4 flex space-x-2">
                    <button onClick={handleRefresh} style={{cursor: "pointer"}}
                            className="bg-white hover:bg-gray-200 text-black font-bold py-2 px-4 rounded-full shadow-md transition duration-300 ease-in-out">
                        刷新⌛️
                    </button>
                    <button onClick={openRechargeDialog} style={{cursor: "pointer"}}
                            className="bg-green-500 hover:bg-green-600 text-white font-bold py-2 px-4 rounded-full shadow-md transition duration-300 ease-in-out">
                        充值💳
                    </button>
                    {/*<button onClick={openRecordDialog} style={{cursor: "pointer"}}*/}
                    {/*        className="bg-blue-500 hover:bg-blue-600 text-white font-bold py-2 px-4 rounded-full shadow-md transition duration-300 ease-in-out">*/}
                    {/*    账户记录📊*/}
                    {/*</button>*/}
                </div>
                <div
                    className="absolute top-4 right-4 bg-white bg-opacity-20 text-white font-bold py-1 px-3 rounded-full shadow-md">
                    用户: {userId}
                </div>


                {/* 充值金额选择对话框 */}
                {isDialogOpen && (
                    <div className="fixed inset-0 flex items-center justify-center bg-black bg-opacity-50 z-50">
                        <div className="bg-white p-6 rounded-lg shadow-lg" style={{ width: '800px' }}>
                            <h2 className="text-xl font-bold mb-4 text-center">选择充值金额</h2>
                            <div className="flex flex-col gap-4">
                                <div className="flex flex-wrap gap-4 mb-4 justify-center">
                                        {amounts.map((amount, index) => (
                                            <button
                                            key={amount}
                                        onClick={() => setSelectedAmount(amount)}
                                        className={`text-white font-bold py-3 px-5 w-40 rounded-lg transition duration-300 ease-in-out ${selectedAmount === amount ? 'bg-blue-500 hover:bg-blue-600' : 'bg-green-500 hover:bg-green-600'}`}
                                    >
                                        <img
                                            src={imagePaths[index]} // 使用索引来获取对应的图片路径
                                            alt="积分图标"
                                            style={{
                                                width: '100px',
                                                height: '80px',
                                                marginRight: '8px'
                                            }}
                                        />
                                        <p style={{color: '#FFD700'}}>积分x{amount * 10}</p> {/* 金色 */}
                                        <p style={{color: 'rgba(0, 0, 0, 1)'}}>{amount} ￥</p> {/* 深天蓝 */}
                                    </button>
                                ))}
                            </div>
                            <div className="info-container">
                                    <span className="highlight">温馨提示：</span>
                                    <span>请复制 <span className="label">支付宝账号</span>，方便后面支付使用</span><br/>
                                <p></p>
                                <p><span className="label">支付宝账号：</span>vqdctm8690@sandbox.com</p>
                                    <p><span className="label">登录密码：</span>111111</p>
                                    <p><span className="label">支付密码：</span>111111</p>
                                </div>
                                <div className="flex justify-center gap-4 mt-4">
                                    <button
                                        onClick={() => handleRecharge(selectedAmount)}
                                        className="bg-blue-500 hover:bg-blue-600 text-white font-bold py-2 px-4 rounded-full transition duration-300 ease-in-out">
                                        确认充值
                                    </button>
                                    <button
                                        onClick={() => setIsDialogOpen(false)}
                                        className="bg-gray-500 hover:bg-gray-600 text-white font-bold py-2 px-4 rounded-full transition duration-300 ease-in-out">
                                        取消充值
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                )}
                {isRecordDialogOpen && (
                    <div className="fixed inset-0 flex items-center justify-center bg-black bg-opacity-50 z-50" style={{zIndex:999}}>
                        <div className="bg-white p-6 rounded-lg shadow-lg" style={{ width: '80%', maxHeight: '90vh', overflow: 'hidden' }}>
                            <h2 className="text-xl font-bold mb-4 text-center">消费记录</h2>
                            <div className="overflow-y-auto max-h-[calc(100vh-150px)]"> {/* 允许垂直滚动 */}
                                <table className="min-w-full divide-y divide-gray-200">
                                    <thead className="bg-gray-100">
                                    <tr>
                                        <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">订单号</th>
                                        <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">消费类型</th>
                                        <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">金额</th>
                                        <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">消费描述</th>
                                        <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">时间</th>
                                    </tr>
                                    </thead>
                                    <tbody className="bg-white divide-y divide-gray-200">
                                    {records.map((record, index) => (
                                        <tr key={index}>
                                            <td className="px-6 py-4 text-sm font-medium text-gray-900">{record.orderNumber}</td>
                                            <td className="px-6 py-4 text-sm text-gray-500">{record.expenseType}</td>
                                            <td className="px-6 py-4 text-sm text-gray-500">{record.amount} ￥</td>
                                            <td className="px-6 py-4 text-sm text-gray-500">{record.description}</td>
                                            <td className="px-6 py-4 text-sm text-gray-500">{formatDate(record.time)}</td>
                                        </tr>
                                    ))}
                                    </tbody>
                                </table>
                            </div>
                            <div className="flex justify-center gap-4 mt-4">
                                <button
                                    onClick={() => setIsRecordDialogOpen(false)}
                                    className="bg-gray-500 hover:bg-gray-600 text-white font-bold py-2 px-4 rounded-full transition duration-300 ease-in-out">
                                    关闭
                                </button>
                            </div>
                        </div>
                    </div>
                )}
            </div>

        </>
    )

}